<template>
  <div class="invoice-detail">
    <a-page-header title="发票详情" @back="router.back()">
      <template #subtitle>
        <div class="status-tag">
          <a-tag :color="sellerName === '顺丰' ? 'blue' : 'green'" style="margin-right: 10px;">{{ sellerName }}</a-tag>
          <a-tag color="gray" v-if="invoiceInfo.status === 'INIT'"
          >未开票
          </a-tag
          >
          <a-tag color="blue" v-if="invoiceInfo.status === 'ADDED'"
          >已开票待验收
          </a-tag
          >
          <a-tag color="green" v-if="invoiceInfo.status === 'FINISHED'"
          >已完成
          </a-tag
          >
        </div>
      </template>
      <template #extra>
        <a-button
            status="danger"
            :size="isPhone ? 'mini' : undefined"
            @click="handleRemoveInvoice"
            v-if="removeBtnShow"
        >删除发票
        </a-button
        >
        <a-button
            type="primary"
            :size="isPhone ? 'mini' : undefined"
            v-if="addBtnShow && !addBtnDisabled"
            @click="addedInvoice"
        >完成开票
        </a-button>
        <a-tooltip content="请先上传发票文件">
          <a-button
              :size="isPhone ? 'mini' : undefined"
              v-if="addBtnShow && addBtnDisabled"
              :disabled="addBtnDisabled"
          >完成开票
          </a-button>
        </a-tooltip>
        <a-button
            type="primary"
            :size="isPhone ? 'mini' : undefined"
            v-if="finishBtnShow"
            @click="finishedInvoice"
        >完成验收
        </a-button
        >
      </template>
    </a-page-header>
    <a-tabs destroy-on-hide>
      <a-tab-pane key="detail" title="发票信息">
        <div class="main" v-if="inited">
          <div class="left-side">
            <a-form
                ref="invoiceFormRef"
                :model="invoiceInfo"
                auto-label-width
                :rules="addRules"
                :layout="isPhone ? 'vertical' : 'horizontal'"
            >
              <a-form-item label="开票名称" field="buyer">
                <a-input
                    v-model="invoiceInfo.buyer"
                    v-if="!infoDisabled"
                ></a-input>
                <span class="text" v-else>{{ invoiceInfo.buyer || "--" }}</span>
              </a-form-item>
              <a-form-item label="税号" field="taxNumber">
                <a-input
                    v-model="invoiceInfo.taxNumber"
                    v-if="!infoDisabled"
                ></a-input>
                <span class="text" v-else>{{
                    invoiceInfo.taxNumber || "--"
                  }}</span>
              </a-form-item>
              <a-form-item label="地址" field="address">
                <a-input
                    v-model="invoiceInfo.address"
                    v-if="!infoDisabled"
                ></a-input>
                <span class="text" v-else>{{
                    invoiceInfo.address || "--"
                  }}</span>
              </a-form-item>
              <a-form-item label="开户银行" field="bank">
                <a-input
                    v-model="invoiceInfo.bank"
                    v-if="!infoDisabled"
                ></a-input>
                <span class="text" v-else>{{ invoiceInfo.bank || "--" }}</span>
              </a-form-item>
              <a-form-item label="银行账号" field="bankAccount">
                <a-input
                    v-model="invoiceInfo.bankAccount"
                    v-if="!infoDisabled"
                ></a-input>
                <span class="text" v-else>{{
                    invoiceInfo.bankAccount || "--"
                  }}</span>
              </a-form-item>
              <a-form-item label="联系电话" field="phone">
                <a-input
                    v-model="invoiceInfo.phone"
                    v-if="!infoDisabled"
                ></a-input>
                <span class="text" v-else>{{ invoiceInfo.phone || "--" }}</span>
              </a-form-item>
              <a-form-item label="开票金额" field="invoiceCount">
                <a-input
                    v-model="invoiceInfo.invoiceCount as string"
                    v-if="!infoDisabled"
                ></a-input>
                <span class="text" v-else>{{
                    invoiceInfo.invoiceCount || "--"
                  }}</span>
              </a-form-item>
              <a-form-item label="发票类型" field="invoiceType">
                <a-select
                    v-model="invoiceInfo.invoiceType"
                    :options="invoiceTypes"
                    v-if="!infoDisabled"
                ></a-select>
                <span class="text" v-else>{{
                    invoiceInfo.invoiceType || "--"
                  }}</span>
              </a-form-item>
              <a-form-item label="月份" field="month">
                <!--                <a-input-->
                <!--                  v-model="invoiceInfo.month"-->
                <!--                  v-if="!infoDisabled"-->
                <!--                ></a-input>-->
                <a-month-picker v-model="invoiceInfo.month" v-if="!infoDisabled" format="YYYY年MM月"
                                style="width: 100%;"></a-month-picker>
                <span class="text" v-else>{{ monthFormat(invoiceInfo.month || '--') || "--" }}</span>
              </a-form-item>
              <a-form-item label="备注" field="remark">
                <a-textarea
                    v-if="!infoDisabled"
                    v-model="invoiceInfo.remark"
                    :auto-size="{ minRows: 3 }"
                    :max-length="500"
                    show-word-limit
                ></a-textarea>
                <span class="text" v-else>{{
                    invoiceInfo.remark || "--"
                  }}</span>
              </a-form-item>
            </a-form>
            <div class="handle-button" v-if="!infoDisabled">
              <a-button @click="router.back()">取消</a-button>
              <a-button type="primary" @click="save">保存</a-button>
            </div>
          </div>
          <div class="right-side" :class="{ 'finished-type': finishStatus }">
            <div class="invoice-title">
              发票文件
              <span
                  style="font-size: 12px; font-weight: initial; color: #999999"
              >（点击文件卡片下载）</span
              >
            </div>
            <a-upload
                :custom-request="handleUpload"
                v-model:file-list="data.fileList"
                @before-remove="beforeRemove"
            >
            </a-upload>
            <pdf-viewer :file-list="data.fileList" :invoice-status="invoiceInfo.status" @remove="viewerRemove"/>
          </div>
        </div>
      </a-tab-pane>
      <a-tab-pane key="track" title="历史记录">
        <history-track
            v-if="inited"
            :invoice-id="invoiceInfo?.id + '' ?? ''"
        ></history-track>
      </a-tab-pane>
      <a-tab-pane key="comment">
        <template #title
        >评论
          <a-badge
              v-if="commentCount > 0"
              :text="Number(commentCount).toString()"
          ></a-badge
          >
        </template>
        <comment
            v-if="invoiceInfo.id"
            v-model:count="commentCount"
            :invoice-id="invoiceInfo.id"
        ></comment>
      </a-tab-pane>
      <a-tab-pane title="发票结构化数据" v-if="['ADDED', 'FINISHED'].includes(<string>invoiceInfo.status)">
        <div class="main">
          <div class="left-side">
            <invoice-struct :invoice-id="String(route.query?.id)" />
          </div>
          <div class="right-side">
            <pdf-viewer :file-list="data.fileList" :invoice-status="invoiceInfo.status" @remove="viewerRemove"/>
          </div>
        </div>
      </a-tab-pane>
    </a-tabs>
  </div>
</template>

<script setup lang="ts">
import {invoiceTypes} from "@/views/invoice/enums";
import {computed, onMounted, ref} from "vue";
import {
  addInvoiceTrack,
  changeAddedStatus,
  finishAddedStatus,
  getById,
  Invoice,
  removeInvoice,
  updateInvoice
} from "@/api/invoiceController";
import {useRoute} from "vue-router";
import router from "@/router/index.js";
import {Message, Modal, RequestOption} from "@arco-design/web-vue";
import axios from "axios";
import {queryFile, removeFile} from "@/api/fileController.ts";
import HistoryTrack from "@/views/invoice/historyTrack.vue";
import {userStore} from "@/store/user.ts";
import {useWindowSize} from "@vueuse/core";
import PdfViewer from "@/views/invoice/pdfViewer.vue";
import Comment from "@/views/invoice/comment.vue";
import {monthFormat} from "@/utils/tools.ts";
import InvoiceStruct from "@/views/invoice/invoiceStruct.vue";

const {width} = useWindowSize();
const isPhone = computed(() => {
  return width.value < 768;
});
const commentCount = ref<number>(0);
const route = useRoute();
const sellerName = computed(() => {
  if (route.name === "发票详情(顺丰)") {
    return "顺丰";
  }
  if (route.name === "发票详情(合丰)") {
    return "合丰";
  }
});
const invoiceInfo = ref<Invoice>({
  buyer: "",
  taxNumber: "",
  address: "",
  bank: "",
  bankAccount: "",
  phone: "",
  invoiceCount: "",
  invoiceType: "",
  month: "",
  remark: "",
  status: "",
  fileKey: "",
});
const invoiceFormRef = ref();
const inited = ref<boolean>(false);
let data = ref({
  fileList: [],
});

const addBtnDisabled = computed(() => {
  return data.value.fileList.length === 0
})

const addRules = ref({
  buyer: [{required: true, message: "请输入开票名称", trigger: "blur"}],
  taxNumber: [{required: true, message: "请输入税号", trigger: "blur"}],
  invoiceCount: [
    {required: true, message: "请输入开票金额", trigger: "blur"},
  ],
  invoiceType: [{required: true, message: "请选择发票类型", trigger: "blur"}],
});

const addBtnShow = computed(() => {
  return invoiceInfo.value.status === "INIT";
});
const finishBtnShow = computed(() => {
  const role = userStore().userInfo?.role || "";
  return (
      invoiceInfo.value.status === "ADDED" &&
      ["管理员", "公司文员"].includes(role)
  );
});
const removeBtnShow = computed(() => {
  const role = userStore().userInfo?.role || "";
  if (role === "管理员") {
    return true;
  }
  if (role === "开票员") {
    return false;
  }
  if (invoiceInfo.value.status === "FINISHED") {
    return false;
  }

  return true;
});
const finishStatus = computed(() => {
  return invoiceInfo.value.status === "FINISHED";
});
const infoDisabled = computed(() => {
  const role = userStore().userInfo?.role || "";
  return invoiceInfo.value.status === "FINISHED" || ["开票员"].includes(role);
});

const init = () => {
  const id = useRoute().query.id as string;
  if (id) {
    getById(id).then((res) => {
      res.invoiceCount = res.invoiceCount + "";
      invoiceInfo.value = res;
      inited.value = true;

      refreshInvoiceFile();
    });
  }
};

const save = () => {
  invoiceFormRef.value.validate((error: boolean) => {
    if (!error) {
      updateInvoice(invoiceInfo.value).then(() => {
        Message.success("保存成功");
        if (sellerName.value === "顺丰") {
          router.push("/invoice_sf");
        }
        if (sellerName.value === "合丰") {
          router.push("/invoice_hf");
        }
      });
    }
  });
};

const handleUpload = (option: RequestOption): any => {
  const {onProgress, onError, onSuccess, fileItem} = option;
  console.log(option, "option");
  var formData = new FormData();
  //@ts-ignore
  formData.append("file", fileItem.file);
  return axios
      .post(
          `${
              import.meta.env.MODE === "development" ? "/api" : ""
          }/file/upload?modelCode=MC001&busiKey=${invoiceInfo.value.fileKey}`,
          formData,
          {
            onUploadProgress: (event) => {
              //@ts-ignore
              onProgress((event.loaded / event.total) * 100);
            },
          }
      )
      .then((res) => {
        console.log(res, "res");
        if (res.status === 200 && res.data.code === 200) {
          addInvoiceTrack({
            invoiceId: invoiceInfo.value.id,
            status: "HANDLE",
            payload: `上传了文件：${fileItem.name}`,
          });
          onSuccess(res);
          refreshInvoiceFile();
          // ocrInvoice(res.data.data.id)
        } else {
          onError(res);
        }
      })
      .catch((err) => {
        onError(err);
      });
};

const viewerRemove = (item: any) => {
  addInvoiceTrack({
    invoiceId: invoiceInfo.value.id,
    status: "HANDLE",
    payload: `删除了文件：${item.name}`,
  });
  refreshInvoiceFile();
};


const beforeRemove = (file: any): Promise<boolean> => {
  return new Promise((resolve, reject) => {
    Modal.confirm({
      title: "提示",
      content: "确定删除该文件吗？删除后将不可找回",
      onOk: () => {
        if (file.response?.id) {
          removeFile(file.response.id)
              .then(() => {
                resolve(true);
                refreshInvoiceFile();
                addInvoiceTrack({
                  invoiceId: invoiceInfo.value.id,
                  status: "HANDLE",
                  payload: `删除了文件：${file.name}`,
                });
              })
              .catch(() => {
                reject(false);
                Message.error("删除失败");
              });
        } else {
          removeFile(file.uid)
              .then(() => {
                resolve(true);
                refreshInvoiceFile();
                addInvoiceTrack({
                  invoiceId: invoiceInfo.value.id,
                  status: "HANDLE",
                  payload: `删除了文件：${file.name}`,
                });
              })
              .catch(() => {
                reject(false);
                Message.error("删除失败");
              });
        }
      },
      onCancel: () => {
        reject(false);
      },
    });
  });
};

const refreshInvoiceFile = () => {
  queryFile("MC001", invoiceInfo.value.fileKey as string).then(
      (res: any[]): void => {
        data.value.fileList = res.map((v: any) => {
          return {
            uid: v.id,
            name: v.fileName,
            url:
                (import.meta.env.MODE === "development" ? "/api" : "") +
                "/file/previewFile?fileId=" +
                v.id,
            downloadCount: v.downloadCount
          };
        }) as any[];
      }
  );
};

const addedInvoice = () => {
  Modal.confirm({
    title: "提示",
    content: "确定完成开票吗？确认后将提交至验收",
    onOk: () => {
      changeAddedStatus(<Invoice>invoiceInfo.value.id)
          .then(() => {
            Message.success("开票完成");
            if (sellerName.value === "顺丰") {
              router.push("/invoice_sf");
            }
            if (sellerName.value === "合丰") {
              router.push("/invoice_hf");
            }
          })
          .catch((err) => {
            Message.error("操作失败：" + err);
          });
    },
  });
};

const finishedInvoice = () => {
  Modal.confirm({
    title: "提示",
    content: "确定完成验收吗？确认后将不能新增、删除发票文件、信息",
    onOk: () => {
      finishAddedStatus(<Invoice>invoiceInfo.value.id)
          .then(() => {
            Message.success("验收完成");
            if (sellerName.value === "顺丰") {
              router.push("/invoice_sf");
            }
            if (sellerName.value === "合丰") {
              router.push("/invoice_hf");
            }
          })
          .catch((err) => {
            Message.error("操作失败：" + err);
          });
    },
  });
};

const handleRemoveInvoice = () => {
  Modal.confirm({
    title: "提示",
    content: "确定删除该发票吗？删除后将不可找回",
    onOk: () => {
      removeInvoice(invoiceInfo.value.id || "").then((res) => {
        if (res) {
          Message.success("删除成功");
          if (sellerName.value === "顺丰") {
            router.push("/invoice_sf");
          }
          if (sellerName.value === "合丰") {
            router.push("/invoice_hf");
          }
        } else {
          Message.error("删除失败");
        }
      });
    },
  });
};
onMounted(() => {
  init();
});
</script>

<style lang="scss" scoped>
.invoice-detail {
  height: 100%;
}

.main {
  display: flex;
  padding-bottom: 50px;

  @media (max-width: 768px) {
    flex-direction: column;
    .left-side,
    .right-side {
      width: calc(100% - 20px) !important;
      padding: 10px !important;
    }
    .right-side {
      margin-top: 20px;
    }
  }

  .left-side {
    width: 40%;
    padding: 0 50px;
    border-right: 1px solid var(--color-neutral-3);
  }

  .right-side {
    width: 60%;
    padding: 0 20px;

    &.finished-type {
      :deep(.arco-upload-wrapper) {
        margin-top: -20px;

        .arco-btn {
          display: none;
        }

        .arco-upload-list-item-operation {
          display: none;
        }

        .arco-upload-icon.arco-upload-icon-success {
          display: none;
        }
      }
    }

    .invoice-title {
      font-size: 16px;
      font-weight: bold;
      margin-bottom: 20px;
    }
  }

  .handle-button {
    text-align: center;
  }

  :deep(.arco-upload-list) {
    display: none;
  }
}
</style>
